%Paul Ozog
% ECE 5666
% Matlab Homework for Ch 7

d1 = 1e-2;
d2 = 1e-3;
cutoffs = [0.2 0.3];
WP = cutoffs(1);
WS = cutoffs(2);
W0 = (WP + WS) / 2;
magnitudes = [1 0];
ripples = [d1 d2];

% Part 1
[N, wn, beta, type] = kaiserord(cutoffs, magnitudes, ripples);

correctionPart1 = 1; %Increment/decrement if specs aren't met

B1 = fir1(N+correctionPart1,wn,type,kaiser(N+1+correctionPart1,beta),'noscale');
A1 = 1;

N + correctionPart1

figure; freqz(B1, A1);

% Part 2
[N, Fo, Ao, weight] = firpmord(cutoffs, magnitudes, ripples);

correctionPart2 = 4; %Increment/decrement if specs aren't met

B2 = firpm(N+correctionPart2, Fo, Ao, weight);
A2 = 1;

N + correctionPart2

figure; freqz(B2, A2);

% Part 3
N = 10;
A3 = 1;

done = 0;
while (~done)
  B3 = fircls1(N, W0, d1, d2, WP, WS, 1);

  passbandMaxIndex = 206; %Pre-calculated index that gives approx
                          %passband limit
  stopbandMinIndex = 308; %Pre-calculated index that gives approx
                          %stopband limit

  [H, w] = freqz(B3, A3, 1024);

  meetsPassbandSpec = abs(abs(H(1:passbandMaxIndex)) - 1) < d1;
  meetsStopbandSpec = abs(H(stopbandMinIndex:end)) < d2;

  if (isempty(find(meetsPassbandSpec == 0)) && ...
      isempty(find(meetsStopbandSpec == 0)))
    done = 1;
    break;
  end
  
  N = N + 1;

end

N

figure; freqz(B3,A3)
